/*
 * @Author: szx
 * @Date: 2021-12-09 13:55:11
 * @LastEditTime: 2021-12-09 14:03:54
 * @Description:
 * @FilePath: \leetcode\剑指offer\05\05.js
 */
/**
 * @param {string} s
 * @return {string}
 */
var replaceSpace = function (s) {
    return s.split(' ').join('%20');
};

var replaceSpace = function (s) {
    // 字符串转为数组
    const strArr = Array.from(s);
    let count = 0;

    // 计算空格数量
    for (let i = 0; i < strArr.length; i++) {
        if (strArr[i] === ' ') {
            count++;
        }
    }
    let right = strArr.length - 1 + 2 * count;
    let left = strArr.length - 1;
    while (left >= 0) {
        if (strArr[left] == ' ') {
            strArr[right--] = '0';
            strArr[right--] = '2';
            strArr[right--] = '%';
            left--;
        } else {
            strArr[right--] = strArr[left--];
        }
    }
    // 数组转字符串
    return strArr.join('');
};
console.log(replaceSpace('we are h'));
